/*
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 *  of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the
 *  Software is furnished to do so, subject to the following conditions:
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 *  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 *  DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 *  OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
 *  THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

package database;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

import utils.Debug;

/**
 * This class represents a website that has a database of objects in space as
 * TLE data and contains the login data needed to retrieve these datasets
 * 
 * @author Benedikt Markt
 * @see SourceDB
 * @see AGILogin
 */
public class SpaceTrackLogin extends SourceDB {

	private static final String siteURL = "https://beta.space-track.org/ajaxauth/login";

	public SpaceTrackLogin() {
		name = "SpaceTrack";
		url = "https://www.space-track.org";
	}

	public SpaceTrackLogin(String username, String password) {
		this.username = username;
		this.password = password;

		name = "SpaceTrack";
		url = "https://www.space-track.org";
	}

	/**
	 * Downloads TLE data and stores it to a file
	 * 
	 * @throws IOException
	 *             if urls are incorrect
	 */
	@Override
	// TODO clean up and stuff
	public void download(String name) throws IOException {
		String loginCredentials = "identity=" + username + "&password="
				+ password;
		String requestURL = "https://beta.space-track.org/basicspacedata/query/class/tle_latest/ORDINAL/1/EPOCH/%3Enow-30/format/3le";

		String sessionCookie = null;

		URL login = new URL(siteURL);

		// open connection to login page
		HttpsURLConnection loginConnection = (HttpsURLConnection) login
				.openConnection();

		loginConnection.setDoOutput(true);
		loginConnection.setDoInput(true);
		loginConnection.setInstanceFollowRedirects(false);
		loginConnection.setRequestMethod("POST");
		loginConnection.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");
		loginConnection.setRequestProperty("charset", "utf-8");
		loginConnection.setRequestProperty("Content-Length",
				"" + Integer.toString(loginCredentials.getBytes().length));
		loginConnection.setUseCaches(false);

		// sending POST request with login data to server
		DataOutputStream wr = new DataOutputStream(
				loginConnection.getOutputStream());
		wr.writeBytes(loginCredentials);
		wr.flush();
		wr.close();

		// obtain session cookie
		String headerName = null;
		for (int i = 1; (headerName = loginConnection.getHeaderFieldKey(i)) != null; i++) {
			if (headerName.equalsIgnoreCase("Set-Cookie")) {
				sessionCookie = loginConnection.getHeaderField(i);
			}
		}

		// fetching data returned from server
		InputStream insLogin = loginConnection.getInputStream();
		InputStreamReader isrLogin = new InputStreamReader(insLogin);
		BufferedReader inLogin = new BufferedReader(isrLogin);
		String inputLineLogin = null;
		while ((inputLineLogin = inLogin.readLine()) != null) {

		}

		// close connection to login page
		loginConnection.disconnect();

		// open connection to requested document
		URL request = new URL(requestURL);
		HttpsURLConnection requestConnection = (HttpsURLConnection) request
				.openConnection();
		// attaching session cookie to request
		requestConnection.setRequestProperty("Cookie", sessionCookie);
		requestConnection.connect();

		// fetching data returned from server
		InputStream ins = requestConnection.getInputStream();
		InputStreamReader isr = new InputStreamReader(ins);
		BufferedReader in = new BufferedReader(isr);

		String inputLine;
		File catalogCato = new File(".\\users\\"
				+ name + "\\catalog.cato");
		FileWriter fstream = new FileWriter(catalogCato);
		BufferedWriter out = new BufferedWriter(fstream);

		while ((inputLine = in.readLine()) != null) {
			out.write(inputLine);
			out.write(System.getProperty("line.separator"));
		}
		out.close();
		in.close();
	}

	/**
	 * Checks if SpaceTrack.org is available
	 * 
	 * @return true if reachable otherwise false;
	 * @throws IOException
	 *             if url is incorrectly formatted
	 */
	@Override
	public boolean isAvailable() throws IOException {
		// TODO find other way than ping, it doesn't work
//		try {
//			return InetAddress.getByName(url).isReachable(3000);
//		} catch (UnknownHostException e) {
//			return false;
//		}
		
		return isCorrectLogin();
	}

	/**
	 * Checks if the given login credentials are correct
	 * 
	 * @return true if correct otherwise false;
	 * @throws IOException
	 */
	@Override
	public boolean isCorrectLogin() {
		// @ TODO doesn't work
		String loginData = "identity=" + username + "&password=" + password;
		try {
		URL login = new URL(siteURL);

		// open connection to login page
		HttpsURLConnection loginConnection = (HttpsURLConnection) login
				.openConnection();

		loginConnection.setDoOutput(true);
		loginConnection.setDoInput(true);
		loginConnection.setInstanceFollowRedirects(false);
		loginConnection.setRequestMethod("POST");

		// sending POST request with login data to server
		DataOutputStream wr = new DataOutputStream(
				loginConnection.getOutputStream());
		wr.writeBytes(loginData);
		wr.flush();
		wr.close();
		// fetching data returned from server
		InputStream ins = loginConnection.getInputStream();
		InputStreamReader isr = new InputStreamReader(ins);
		BufferedReader in = new BufferedReader(isr);
		String inputLine = null;
		while ((inputLine = in.readLine()) != null) {
			if(inputLine.contains("Failed")) {
				return false;
			}

		}

		loginConnection.disconnect();
		
		} catch (IOException e) {
			return false;
		}
		return true;
	}

}
